package myzd.api.utils;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author Administrator
 */
@Slf4j
public class Pinyin4jUtil {
  public static Collection<String> getPinyinCollection(String chinese) {
    Set<String> pinyins = null;
    if (Constant.USE_POLYPHONE) {
      List<String[]> pinyinList = new ArrayList<>();
      String[] array;
      for (int i = 0; i < chinese.length(); ++i) {
        array = PinyinHelper.convertToPinyinArray(chinese.charAt(i), PinyinFormat.WITHOUT_TONE);
        if (array != null && array.length > 0) {
          pinyinList.add(array);
        }
      }
      for (String[] array2 : pinyinList) {
        if (pinyins != null && !pinyins.isEmpty()) {
          Set<String> pres = pinyins;
          pinyins = new HashSet<>();
          for (String pre : pres) {
            for (String string : array2) {
              pinyins.add(pre + string);
            }
          }
        } else {
          pinyins = new HashSet<>();
          pinyins.addAll(Arrays.asList(array2));
        }
      }

      return pinyins;
    } else {
      return new HashSet<String>() {{
        try {
          add(PinyinHelper.convertToPinyinString(chinese, "", PinyinFormat.WITHOUT_TONE));
        } catch (PinyinException e) {
          log.warn("PinyinException", e);
        }
      }};
    }


  }

  static Collection<String> getPinyinShortCollection(String chinese) {
    Set<String> sorts = new HashSet<>();
    if (Constant.USE_POLYPHONE) {
      List<String[]> pinyinList = new ArrayList<>();
      for (int i = 0; i < chinese.length(); ++i) {
        String[] pinyinArray = PinyinHelper.convertToPinyinArray(chinese.charAt(i), PinyinFormat.WITHOUT_TONE);
        if (pinyinArray != null && pinyinArray.length > 0) {
          pinyinList.add(pinyinArray);
        }
      }
      Set<String> pinyins = null;
      for (String[] array : pinyinList) {
        if (pinyins != null && !pinyins.isEmpty()) {
          Set<String> pres = pinyins;
          pinyins = new HashSet<>();
          for (String pre : pres) {
            for (String string : array) {
              pinyins.add(pre + string.substring(0, 1));
              sorts.add(pre + string.substring(0, 1));
            }
          }
        } else {
          pinyins = new HashSet<>();
          for (String string : array) {
            pinyins.add(string.substring(0, 1));
            sorts.add(string.substring(0, 1));
          }
        }
      }
      return sorts;
    } else {

      return new HashSet<String>() {{
        try {
          add(PinyinHelper.getShortPinyin(chinese));
        } catch (PinyinException e) {
          e.printStackTrace();
        }
      }};
    }


  }


}
